﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Dielectrics : Material
{
    public float ref_idx;
    public Dielectrics(float ref_idx)
    {
        this.ref_idx = ref_idx;
    }
    public override bool scatter(Ray ray, HitRecord record, ref Color attaenuation, ref Ray scattered)
    {
        Vector3 outward_normal;
        Vector3 reflected = _M.Reflect(ray.direction, record.normal);
        float ni_over_nt =1;
        attaenuation =Color.white;
        Vector3 refracted = Vector3.zero;
        float cos = 0;
        float reflect_prob = 0;
        if (Vector3.Dot(ray.direction, record.normal) > 0) //从内部折射
        {
            outward_normal = -record.normal;
            ni_over_nt = ref_idx;
            cos = ni_over_nt * Vector3.Dot(ray.normalDirection, record.normal);
        }
        else //从外部折射
        {
            outward_normal = record.normal;
            ni_over_nt = 1f / ref_idx;
            cos = -Vector3.Dot(ray.normalDirection, record.normal);
        }
        if (_M.Refract(ray.direction, outward_normal, ni_over_nt, ref refracted))
        {
            //scattered = new Ray(record.p, reflected);
            reflect_prob = _M.schlick(cos, ni_over_nt);
        }
        else
        {
            reflect_prob = 1;
           // scattered = new Ray(record.p, reflected);
            return false;
        }

        //因为一条光线只会采样一个点，所以这里就用蒙特卡洛模拟的方法，用概率去决定数值
        if (UnityEngine.Random.Range(0f, 1f) <= reflect_prob)
        {
            scattered  = new Ray(record.p, reflected);
        }
        else
        {
            scattered  = new Ray(record.p, refracted);
        }

        return true;
    }
}
